package com.andy.qhb.action;

import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.dao.vo.Where;
import com.andy.qhb.entity.UsrFriends;
import com.andy.qhb.entity.UsrGameInfo;
import com.andy.qhb.entity.UsrUser;
import com.andy.qhb.game.GameUtils;
import com.andy.qhb.game.GameConf;
import com.andy.qhb.game.GameUser;
import com.andy.qhb.game.Global;
import com.andy.qhb.utils.GmAction;
import com.andy.qhb.utils.GoConstant;
import com.andy.qhb.utils.SendUtil;
import com.andy.qhb.websocket.MySocketSession;

/**
 * 登录逻辑
 * @author cuiwm
 *
 */
@Component(GmAction.ACTION_PREFIX+GmAction.ACTION_100)
public class LoginAction implements IWebAction{

	@Override
	public void doAction(MySocketSession myWebSocket, Map<String, Object> data) {
		String userName = MapUtils.getString(data, "userName");
		UsrUser user = null;
		UsrGameInfo gameInfo = null;
		UsrFriends friends = null;
		if(StringUtils.isBlank(userName))return;
		
		user = DaoUtils.getOne(UsrUser.class, Where.eq("user_Name", userName));
		if(user == null){
			user = new UsrUser();
			user.setUserName(RandomStringUtils.randomAlphabetic(10));
			user.setNickName(GameUtils.genNickName());
			user.setIcon(String.valueOf(RandomUtils.nextInt(0, 10)));
			DaoUtils.insert(user);
			
			gameInfo = new UsrGameInfo();
			gameInfo.setUid(user.getId());
			gameInfo.addCoin(GameConf.getConfInt("init_coin"));
			gameInfo.setWinCount(0);
			gameInfo.setLoseCount(0);
			DaoUtils.insert(gameInfo);
			
			friends = new UsrFriends();
			friends.setUid(user.getId());
			DaoUtils.insert(friends);
			
		}else{
			gameInfo = DaoUtils.getOne(UsrGameInfo.class, Where.eq("uid", user.getId()));
		}
		GameUser gameUser = new GameUser(user);
		gameUser.setGameInfo(gameInfo);
		gameUser.setFriends(friends);
		
		Global.addUser(user.getId(), myWebSocket);
		myWebSocket.setAttr(GoConstant.USER_SESSION_KEY, gameUser);
		
		SendUtil.send100(myWebSocket, gameUser);
		SendUtil.send110(myWebSocket, gameUser);
	}

	
	
	
}
